package com.tju.resource.oauth.controller.tb;

import com.tju.resource.annotation.Log;
import com.tju.resource.business.tb_retreat.TbRetreatService;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbOrderMapper;
import com.tju.resource.model.TbOrder;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.business.tb_order.TbOrderService;
import com.tju.resource.business.tb_prod_plan.TbProdPlanService;
import com.tju.resource.model.TbRetreat;
import com.tju.resource.result.Result;
import com.tju.resource.tool.enum_utils.FunctionType;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import com.tju.resource.tool.tool.QuickQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

@RestController
public class TbProdPlanController {

    public static final String prefix = "poplan";

    @Autowired
    TbProdPlanService service;
    @Autowired
    TbOrderMapper orderMapper;
    @Autowired
    private TbRetreatService tbRetreatService;

    @Autowired
    TbOrderService oService;
    @Autowired
    TbOrderService tbOrderService;
//    @Autowired
//    private TbSendMatlService tbSendMatlService;

    @PostMapping(prefix + "/getAll")
    @Log(type = FunctionType.List)
    @PreAuthorize("hasAnyAuthority('sys:plan:project:list','sys:project:list')")
    public Result<Object> getAll(@RequestBody ClientParameters params) {
        return service.getAll(params);
    }

    @PostMapping(prefix + "/add")
    @Log(type = FunctionType.Add)
    @PreAuthorize("hasAuthority('sys:plan:project:add')")
    public Result<Object> add(@RequestBody TbProdPlan plan) {
        return baseVerify(plan, pl -> service.add(pl));
    }

    @PostMapping(prefix + "/upd")
    @Log(type = FunctionType.Modify)
    @PreAuthorize("hasAnyAuthority('sys:plan:project:edit','sys:project:edit')")
    public Result<Object> upd(@RequestBody TbProdPlan plan) {
        return baseVerify(plan, pl -> {
            TbProdPlan tbProdPlan = service.get(pl.getId());
            if (EmptyUtils.isNotEmpty(tbProdPlan)) {
                if (QuickQuery.list(orderMapper, QuickQuery.params().putOnce("order_number", plan.getOrderNumber())).size() == 0) {
                    throw new ServiceException("订单号不存在!");
                } else {
                    return service.upd(pl);
                }
            } else {
                throw new ServiceException("生产计划不存在!");
            }

        });
    }

    @PostMapping(prefix + "/del")
    @Log(type = FunctionType.Delete)
    @PreAuthorize("hasAuthority('sys:plan:project:delete')")
    public Result<Object> del(@RequestBody TbProdPlan plan) {
        if (null != service.get(plan.getId())) {
            return service.del(plan);
        } else {
            throw new ServiceException("该生产计划不存在!");
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends TbProdPlan, R extends Result<Object>> R baseVerify(T plan, Function<T, R> f) {
        Objects.requireNonNull(plan);
        Objects.requireNonNull(f);

        ClientParameters params = new ClientParameters();

        if (null != plan.getOrderNumber() && !StringUtils.equals(plan.getOrderNumber(), "")) {
            List<TbOrder> objectResult;

            params.setOne(plan.getOrderNumber());
            params.setLimit(10);
            params.setPage(1);

            objectResult = QuickQuery.list(orderMapper, QuickQuery.params().putOnce("order_number", plan.getOrderNumber()));

            if (null == objectResult || 0 == objectResult.size()) {
                throw new ServiceException("订单号不存在!");
            } else {
                return f.apply(plan);
            }
        } else {
            throw new ServiceException("订单号不可为空!");
        }
    }

    public boolean checkDupGN(TbProdPlan pl) {
        TbOrder tbOrder = tbOrderService.checkOrderNumberUnique(pl.getOrderNumber());
        List<TbProdPlan> plans = service.getByOR(tbOrder.getId());
        AtomicReference<Boolean> dupFlag = new AtomicReference<>(false);

        plans.forEach(ele -> {
            if (StringUtils.equals(ele.getGoodsName(), pl.getGoodsName())) {
                dupFlag.set(true);
            }
        });

        return dupFlag.get();
    }

    /**
     * 修改该订单为审核通过
     */
    @PostMapping(prefix + "/updateFinished")
    @PreAuthorize("hasAuthority('sys:plan:project:approve')")
    @Log(type = FunctionType.Modify)
    public Result<Object> updateFinished(@RequestBody TbProdPlan plan) {
        return service.updateFinished(plan);
    }

    /**
     * 根据生产型号
     *
     * @param params
     * @return
     */
    @PostMapping(prefix + "/getProdPlan")
    //@PreAuthorize("hasAuthority('sys:plan:project:list')")
    @Log(type = FunctionType.List)
    public Result<Object> getProdPlan(@RequestBody Map<String, String> params) {
        return service.getProdPlan(params);
    }
    /**
     * 耗材退料或原料退料
     * @param tbRetreatList 参数
     * @return 结果
     */
    @PostMapping(prefix + "/back")
    @Log(type = FunctionType.ReturnMaterial)
    @PreAuthorize("hasAnyAuthority('sys:plan:project:back','')")
    public Result<Object> backConsumablesAndRmRetreat(@RequestBody  TbRetreat tbRetreatList) {
        return tbRetreatService.addRetreatList(tbRetreatList);
    }
    /**
     * 根据生产计划id查询原料
     * @param tbRetreat 参数
     * @return 结果
     */
    @PostMapping(prefix + "/selectRm")
    @PreAuthorize("hasAnyAuthority('sys:plan:project:list','sys:project:list','sys:plan:project:back')")
    @Log(type = FunctionType.List)
    public Result<Object> selectRm(@RequestBody Map<String,String> tbRetreat) {
        return tbRetreatService.selectRm(tbRetreat);
    }
    /**
     * 根据生产计划id查询耗材
     * @param tbRetreat 参数
     * @return 结果
     */
    @PostMapping(prefix + "/selectConsumables")
    @PreAuthorize("hasAnyAuthority('sys:plan:project:list','sys:project:list','sys:plan:project:back')")
    @Log(type = FunctionType.List)
    public Result<Object> selectConsumables(@RequestBody Map<String,String> tbRetreat) {
        return tbRetreatService.selectConsumables(tbRetreat);
    }
    /**
     *  生产计划分配耗材
     */
    @PostMapping(prefix + "/addConsumables")
    @Log(type = FunctionType.ProdPlanAddConsumables)
    @PreAuthorize("hasAuthority('sys:plan:project:add')")
    public Result<Object> addConsumables(@RequestBody TbProdPlan prodPlan){
        return service.addConsumables(prodPlan);
    }
}
